package com.wing.cabinet.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.cabinet.dao.CellInventorySpaceDao;
import com.wing.cabinet.model.entity.*;
import com.wing.cabinet.model.request.CellInventorySpaceForm;
import com.wing.cabinet.model.request.UseInventoryInoutDetailForm;
import com.wing.cabinet.model.response.*;
import com.wing.common.exception.BusinessException;
import com.wing.common.utils.JsonResult;
import com.wing.order.service.InventoryAlarmService;
import com.wing.setting.model.entity.SystemRuleInfo;
import com.wing.setting.service.SystemRuleInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 售刀柜产品货道库存-ServiceImpl
 *
 * @author
 */
@Service
@Slf4j
public class CellInventorySpaceServiceImpl extends ServiceImpl<CellInventorySpaceDao, CellInventorySpace> implements CellInventorySpaceService {

    @Autowired
    private InventoryAlarmService inventoryAlarmService;

    @Autowired
    private CabAlarmSettingsService cabAlarmSettingsService;

    @Autowired
    private StorageInventoryInoutDetailService storageInventoryInoutDetailService;

    @Autowired
    private SystemRuleInfoService systemRuleInfoService;

    @Autowired
    private StorageInventorySpaceService storageInventorySpaceService;


    @Override
    public int add(CellInventorySpaceForm cellInventorySpaceForm) {

        //校验

        CellInventorySpace cellInventorySpace =new CellInventorySpace();
        CopyOptions copyOptions = CopyOptions.create()
        .setEditable(CellInventorySpace.class)
        .setIgnoreError(true)
        .setIgnoreNullValue(true);
        BeanUtil.copyProperties(cellInventorySpaceForm, cellInventorySpace, copyOptions);

        return baseMapper.insert(cellInventorySpace);
    }

    @Override
    public List<CellInventorySpaceVO> list4app(Map<String, Object> params) {
        return baseMapper.list4app(params);
    }

    @Override
    public List<CellInventorySpaceVO> listSKU4app(Map<String, Object> params) {
        return baseMapper.listSKU4app(params);
    }

    @Override
    public List<CellInventorySpaceVO> listOptimalSpace4app(Map<String, Object> params) {
        return baseMapper.listOptimalSpace4app(params);
    }

    @Override
    public Page<CellInventorySpaceVO> pageList4app(Page page, Map<String, Object> params) {
        List<CellInventorySpaceVO> list = baseMapper.list4app(page, params);
        page.setRecords(list);
        return page;
    }

    @Override
    public Page<CellInventorySpaceVO> pageListSKU4app(Page page, Map<String, Object> params) {
        List<CellInventorySpaceVO> list = baseMapper.listSKU4app(page, params);
        page.setRecords(list);
        return page;
    }

    @Override
    public Page<CellInventorySpaceVO> pageList(Page page, Map<String, Object> params) {
        List<CellInventorySpaceVO> list = baseMapper.list(page, params);
        page.setRecords(list);
        return page;
    }

    @Override
    public JsonResult<List<CellInventorySpaceVO>> getSpaces(UseInventoryInoutDetailForm useInventoryInoutDetailForm) {
        try{
            List<CellInventorySpaceVO> resultList=new ArrayList<>();
//            CabinetCargoSpaceVO spaceVO = storageInventoryInoutDetailService.getUsableSpaces(useInventoryInoutDetailForm, StorageInventoryInout.BusinessType.recycle);
//            if (spaceVO == null) {
//                if(CabinetCargoSpace.SpaceNature.personal.equals(useInventoryInoutDetailForm.getStorageType())){
//                    return JsonResult.fail("未找到可用的专属库位,请先进行库位设置",new ArrayList<>());
//                }else if(CabinetCargoSpace.SpaceNature.specialClass.equals(useInventoryInoutDetailForm.getStorageType())){
//                    return JsonResult.fail("未找到可用的专类库位，请先进行库位设置",new ArrayList<>());
//                }else if(CabinetCargoSpace.SpaceNature.common.equals(useInventoryInoutDetailForm.getStorageType())){
//                    return JsonResult.fail("未找到可用的公共库位",new ArrayList<>());
//                }else{
//                    return JsonResult.fail("存贮性质参数错误",new ArrayList<>());
//                }
//            }
//            CabinetCargoSpaceVO spaceVO = storageInventoryInoutDetailService.getSpaces4OldNew(null,useInventoryInoutDetailForm.getCabCode(),useInventoryInoutDetailForm.getSkuCode(),StorageInventoryInout.BusinessType.jsonCreator(useInventoryInoutDetailForm.getSpaceType().name()));
            CabinetCargoSpaceVO spaceVO = storageInventoryInoutDetailService.getSpaces4OldNew(null,useInventoryInoutDetailForm.getCabCode(),useInventoryInoutDetailForm.getSkuCode(),StorageInventoryInout.BusinessType.jsonCreator(useInventoryInoutDetailForm.getSpaceType().name()),useInventoryInoutDetailForm.getQuantity());
            if (spaceVO==null){
                return JsonResult.fail("未找到可用的库位",new ArrayList<>());
            }
            spaceVO.setSpaceCode(spaceVO.getCode());
            Map paramMap=new HashMap();
            String[] cabCodes=useInventoryInoutDetailForm.getCabCode().split(",");
            paramMap.put("skuCode4app",useInventoryInoutDetailForm.getSkuCode());
            paramMap.put("cabCodes",cabCodes);
            paramMap.put("quantityPackUnit",useInventoryInoutDetailForm.getQuantity());
            List<CellInventorySpaceVO> cellInventorySpaceVOS=baseMapper.list4app(paramMap);

            CellInventorySpaceVO storageSpaceVO=new CellInventorySpaceVO();
            storageSpaceVO.setCabCode(spaceVO.getCabCode());
            storageSpaceVO.setSpaceCode(spaceVO.getCode());
            resultList.add(storageSpaceVO);

            if (cellInventorySpaceVOS.size()==0){
                Map paramMap2=new HashMap();
                paramMap2.put("skuCode4app",useInventoryInoutDetailForm.getSkuCode());
                paramMap2.put("cabCodes",cabCodes);
                paramMap2.put("businessType",StorageInventorySpace.BusinessType.exhibit.getValue());
                paramMap2.put("quantityPackUnit",useInventoryInoutDetailForm.getQuantity());
                List<StorageInventorySpaceVO> storageInventorySpaceVOS=storageInventorySpaceService.list4app(paramMap2);
                if (storageInventorySpaceVOS.size()==0){
                    return JsonResult.fail("SKU["+useInventoryInoutDetailForm.getSkuCode()+"],包装数量["+useInventoryInoutDetailForm.getQuantity()+"]的没有货可换",new ArrayList<>());
                }
                CellInventorySpaceVO cellInventorySpaceVO=new CellInventorySpaceVO();
                BeanUtils.copyProperties(storageInventorySpaceVOS.get(0),cellInventorySpaceVO);
                cellInventorySpaceVO.setQuantity(1);
                resultList.add(cellInventorySpaceVO);
            }else{
                resultList.add(cellInventorySpaceVOS.get(0));
            }

            return JsonResult.success(resultList);

        }catch (Exception e){
            log.error("get recycle space fail",e);
            return JsonResult.fail(e.getMessage(),new ArrayList<>());
        }
    }

    @Override
    public JsonResult<OldNewSpaceVO> getSpaces4MoreKnife(UseInventoryInoutDetailForm useInventoryInoutDetailForm) {
        try{
            OldNewSpaceVO oldNewSpaceVO=new OldNewSpaceVO();
//            CabinetCargoSpaceVO spaceVO = storageInventoryInoutDetailService.getUsableSpaces(useInventoryInoutDetailForm, StorageInventoryInout.BusinessType.recycle);
//            if (spaceVO == null) {
//                if(CabinetCargoSpace.SpaceNature.personal.equals(useInventoryInoutDetailForm.getStorageType())){
//                    return JsonResult.fail("未找到可用的专属库位,请先进行库位设置",new ArrayList<>());
//                }else if(CabinetCargoSpace.SpaceNature.specialClass.equals(useInventoryInoutDetailForm.getStorageType())){
//                    return JsonResult.fail("未找到可用的专类库位，请先进行库位设置",new ArrayList<>());
//                }else if(CabinetCargoSpace.SpaceNature.common.equals(useInventoryInoutDetailForm.getStorageType())){
//                    return JsonResult.fail("未找到可用的公共库位",new ArrayList<>());
//                }else{
//                    return JsonResult.fail("存贮性质参数错误",new ArrayList<>());
//                }
//            }
//            CabinetCargoSpaceVO spaceVO = storageInventoryInoutDetailService.getSpaces4OldNew(null,useInventoryInoutDetailForm.getCabCode(),useInventoryInoutDetailForm.getSkuCode(),StorageInventoryInout.BusinessType.jsonCreator(useInventoryInoutDetailForm.getSpaceType().name()));
            List<String> skuCodes=new ArrayList<>();
            Integer quantity=0;
            for (UseInventoryInoutDetailForm item:useInventoryInoutDetailForm.getDetailList()){
                skuCodes.add(item.getSkuCode());
                quantity+=item.getQuantity();
            }
//            useInventoryInoutDetailForm.setSkuCodes(skuCodes);
//            useInventoryInoutDetailForm.setQuantity(quantity);
            CabinetCargoSpaceVO spaceVO = storageInventoryInoutDetailService.getSpaces4OldNewMoreKnife(null,useInventoryInoutDetailForm.getCabCode(),skuCodes,StorageInventoryInout.BusinessType.jsonCreator(useInventoryInoutDetailForm.getSpaceType().name()),quantity);
            if (spaceVO==null){
                return JsonResult.fail("未找到可用的库位",new ArrayList<>());
            }
            oldNewSpaceVO.setCargoSpace(spaceVO);
            List<UseInventoryInoutDetailForm> skuLaneList=getOptimalSpaces(useInventoryInoutDetailForm);
            oldNewSpaceVO.setSkuLaneList(skuLaneList);
            return JsonResult.success(oldNewSpaceVO);
        }catch (Exception e){
            log.error("get recycle space fail",e);
            return JsonResult.fail(e.getMessage(),new ArrayList<>());
        }
    }

    @Override
    public JsonResult<OldNewSpaceVO> getUserSpaces(UseInventoryInoutDetailForm useInventoryInoutDetailForm) {
        try{
//            CabinetCargoSpaceVO spaceVOList = storageInventoryInoutDetailService.getUsableSpaces(useInventoryInoutDetailForm, StorageInventoryInout.BusinessType.recycle);
//            if (spaceVOList == null) {
//                if(CabinetCargoSpace.SpaceNature.personal.equals(useInventoryInoutDetailForm.getStorageType())){
//                    return JsonResult.fail("未找到可用的专属库位,请先进行库位设置",new ArrayList<>());
//                }else if(CabinetCargoSpace.SpaceNature.specialClass.equals(useInventoryInoutDetailForm.getStorageType())){
//                    return JsonResult.fail("未找到可用的专类库位，请先进行库位设置",new ArrayList<>());
//                }else if(CabinetCargoSpace.SpaceNature.common.equals(useInventoryInoutDetailForm.getStorageType())){
//                    return JsonResult.fail("未找到可用的公共库位",new ArrayList<>());
//                }else{
//                    return JsonResult.fail("存贮性质参数错误",new ArrayList<>());
//                }
//            }
            OldNewSpaceVO oldNewSpaceVO=new OldNewSpaceVO();
//            CabinetCargoSpaceVO spaceVOList = storageInventoryInoutDetailService.getUserSpaces(null,useInventoryInoutDetailForm.getCabCode(),useInventoryInoutDetailForm.getSkuCode(),StorageInventoryInout.BusinessType.jsonCreator(useInventoryInoutDetailForm.getSpaceType().name()));
            List<Integer> spaceTypes=new ArrayList<>();
            spaceTypes.add(CabinetCargoSpace.SpaceType.common.getValue());
            spaceTypes.add(CabinetCargoSpace.SpaceType.temp.getValue());
            CabSpaceResultVO cabSpaceResultVO = storageInventoryInoutDetailService.getUserSpaces(useInventoryInoutDetailForm.getStorageType(),useInventoryInoutDetailForm.getCabCode(),useInventoryInoutDetailForm.getSkuCode(), StorageInventoryInout.BusinessType.temp,spaceTypes);
            List<CabinetCargoSpaceVO> spaceVOList=cabSpaceResultVO.getList();
            if (spaceVOList.size()==0){
                if (cabSpaceResultVO.getIsHasUserSpace()){
                    return JsonResult.fail("当前用户分配的专属库位已经存满，请联系管理员新增专属格子",new OldNewSpaceVO());
                }else{
                    return JsonResult.fail("暂未配置当前用户的专属库位，请联系管理员新增专属格子",new OldNewSpaceVO());
                }

            }
            spaceVOList.forEach(item->{item.setSpaceCode(item.getCode());});
            oldNewSpaceVO.setCargoSpaces(spaceVOList);
            Map paramMap=new HashMap();
            String[] cabCodes=useInventoryInoutDetailForm.getCabCode().split(",");
            paramMap.put("skuCode4app",useInventoryInoutDetailForm.getSkuCode());
            paramMap.put("quantityPackUnit",useInventoryInoutDetailForm.getQuantity());
            paramMap.put("cabCodes",cabCodes);
            List<CellInventorySpaceVO> cellInventorySpaceVOS=baseMapper.list4app(paramMap);
            if (cellInventorySpaceVOS.size()==0){
//                return JsonResult.fail("SKU["+useInventoryInoutDetailForm.getSkuCode()+"]没有货可换");
                Map paramMap2=new HashMap();
                paramMap2.put("skuCode4app",useInventoryInoutDetailForm.getSkuCode());
                paramMap2.put("cabCodes",cabCodes);
                paramMap2.put("quantityPackUnit",useInventoryInoutDetailForm.getQuantity());
                paramMap2.put("businessType",StorageInventorySpace.BusinessType.exhibit.getValue());
                List<StorageInventorySpaceVO> storageInventorySpaceVOS=storageInventorySpaceService.list4app(paramMap2);
                if (storageInventorySpaceVOS.size()==0){
                    return JsonResult.fail("SKU["+useInventoryInoutDetailForm.getSkuCode()+"]没有货可换",new OldNewSpaceVO());
                }
                CellInventorySpaceVO cellInventorySpaceVO=new CellInventorySpaceVO();
                BeanUtils.copyProperties(storageInventorySpaceVOS.get(0),cellInventorySpaceVO);
                cellInventorySpaceVO.setQuantity(1);
                oldNewSpaceVO.setLaneSpace(cellInventorySpaceVO);
            }else{
                oldNewSpaceVO.setLaneSpace(cellInventorySpaceVOS.get(0));
            }
            return JsonResult.success(oldNewSpaceVO);
        }catch (Exception e){
            log.error("get recycle space fail",e);
            return JsonResult.fail(e.getMessage(),new OldNewSpaceVO());
        }
    }



    @Override
    public JsonResult<OldNewSpaceVO> getUserSpaces4MoreKnife(UseInventoryInoutDetailForm useInventoryInoutDetailForm) {
        try{
//            CabinetCargoSpaceVO spaceVOList = storageInventoryInoutDetailService.getUsableSpaces(useInventoryInoutDetailForm, StorageInventoryInout.BusinessType.recycle);
//            if (spaceVOList == null) {
//                if(CabinetCargoSpace.SpaceNature.personal.equals(useInventoryInoutDetailForm.getStorageType())){
//                    return JsonResult.fail("未找到可用的专属库位,请先进行库位设置",new ArrayList<>());
//                }else if(CabinetCargoSpace.SpaceNature.specialClass.equals(useInventoryInoutDetailForm.getStorageType())){
//                    return JsonResult.fail("未找到可用的专类库位，请先进行库位设置",new ArrayList<>());
//                }else if(CabinetCargoSpace.SpaceNature.common.equals(useInventoryInoutDetailForm.getStorageType())){
//                    return JsonResult.fail("未找到可用的公共库位",new ArrayList<>());
//                }else{
//                    return JsonResult.fail("存贮性质参数错误",new ArrayList<>());
//                }
//            }
            OldNewSpaceVO oldNewSpaceVO=new OldNewSpaceVO();
//            CabinetCargoSpaceVO spaceVOList = storageInventoryInoutDetailService.getUserSpaces(null,useInventoryInoutDetailForm.getCabCode(),useInventoryInoutDetailForm.getSkuCode(),StorageInventoryInout.BusinessType.jsonCreator(useInventoryInoutDetailForm.getSpaceType().name()));
            List<Integer> spaceTypes=new ArrayList<>();
            spaceTypes.add(CabinetCargoSpace.SpaceType.common.getValue());
            spaceTypes.add(CabinetCargoSpace.SpaceType.temp.getValue());

            List<String> skuCodes=new ArrayList<>();
            Integer quantity=0;
            for (UseInventoryInoutDetailForm item:useInventoryInoutDetailForm.getDetailList()){
                skuCodes.add(item.getSkuCode());
                quantity+=item.getQuantity();
            }
            CabSpaceResultVO cabSpaceResultVO = storageInventoryInoutDetailService.getUserSpaces(useInventoryInoutDetailForm.getStorageType(),useInventoryInoutDetailForm.getCabCode(),skuCodes, StorageInventoryInout.BusinessType.temp,spaceTypes,quantity);

            List<CabinetCargoSpaceVO> spaceVOList=cabSpaceResultVO.getList();
            if (spaceVOList.size()==0){
                if (cabSpaceResultVO.getIsHasUserSpace()){
                    return JsonResult.fail("当前用户分配的专属库位已经存满，请联系管理员新增专属格子",new OldNewSpaceVO());
                }else{
                    return JsonResult.fail("暂未配置当前用户的专属库位，请联系管理员新增专属格子",new OldNewSpaceVO());
                }

            }
            spaceVOList.forEach(item->{item.setSpaceCode(item.getCode());});
            oldNewSpaceVO.setCargoSpaces(spaceVOList);

            List<UseInventoryInoutDetailForm> skuLaneList=getOptimalSpaces(useInventoryInoutDetailForm);
            oldNewSpaceVO.setSkuLaneList(skuLaneList);
            return JsonResult.success(oldNewSpaceVO);
        }catch (Exception e){
            log.error("get recycle space fail",e);
            return JsonResult.fail(e.getMessage(),new ArrayList<>());
        }
    }



    public List<UseInventoryInoutDetailForm> getOptimalSpaces(UseInventoryInoutDetailForm useInventoryInoutDetailForm) {
//        SystemRuleInfo systemRuleInfo=systemRuleInfoService.getOne(new QueryWrapper<SystemRuleInfo>());
        SystemRuleInfo systemRuleInfo=systemRuleInfoService.getRuleInfo();
        Boolean outOrderFlag=true;
        if (systemRuleInfo!=null){
            outOrderFlag=systemRuleInfo.getOutOrderFlag();
        }
        Map paramMap=new HashMap();
        String[] cabCodes=useInventoryInoutDetailForm.getCabCode().split(",");
        for (UseInventoryInoutDetailForm item:useInventoryInoutDetailForm.getDetailList()){
            paramMap.put("skuCode4app",item.getSkuCode());
            paramMap.put("cabCodes",cabCodes);
            paramMap.put("quantityPackUnit",item.getQuantityPackUnit());
            paramMap.put("sort","asc");
//                paramMap.put("quantity4Query",item.getQuantity());
            List<CellInventorySpaceVO> cellInventorySpaceVOS=baseMapper.listOptimalSpace4app(paramMap);
            if (cellInventorySpaceVOS.size()==0||getSumQuantity(cellInventorySpaceVOS)<item.getQuantity()){
                throw new BusinessException("SKU["+item.getSkuCode()+"],包装规格数量["+useInventoryInoutDetailForm.getQuantityPackUnit()+"]货不足");
            }
            item.setLaneList(cellInventorySpaceVOS);

            Map<String,List<CellInventorySpaceVO>> spaceMap= getAvaiableCab(item.getLaneList(),item.getQuantity());
            item.setCabSpacesMap(spaceMap);
            item.setCabCodesSet(spaceMap.keySet());
        }

        String optimalCabCode=getOptimalCab(useInventoryInoutDetailForm.getDetailList());
        for (UseInventoryInoutDetailForm item:useInventoryInoutDetailForm.getDetailList()){
            if (item.getCabSpacesMap().containsKey(optimalCabCode)){
                List<CellInventorySpaceVO> sortList=item.getCabSpacesMap().get(optimalCabCode);
                Collections.sort(sortList);
                item.setResultLaneList(sortList);
            }else{
                if (item.getCabCodesSet().size()>0){
                    List<CellInventorySpaceVO> sortList=item.getCabSpacesMap().get(item.getCabCodesSet().iterator().next());
                    Collections.sort(sortList);
                    item.setResultLaneList(sortList);
                }else{
                    item.setResultLaneList(item.getLaneList());
                    List<CabSortInventorySpaceVO> sortList=getCabSpaces(item.getLaneList());
                    Collections.sort(sortList);
                    item.setSortCabList(sortList);
                }

            }
            if (outOrderFlag){
                item.setResultLaneList(getSpaceByLanePullFull(item));
            }else{
                item.setResultLaneList(getSpaceByLanePoll(item,optimalCabCode));
            }
        }
        useInventoryInoutDetailForm.getDetailList().forEach(e->{
            e.setLaneList(null);
            e.setCabSpacesMap(null);
            e.setCabCodesSet(null);
            e.setSortCabList(null);
            //test
            e.setQuantityResult(getSumQuantity(e.getResultLaneList()));
            if (!e.getQuantity().equals(e.getQuantityResult())){
                log.error("get optimal space fail:{}","SKU["+e.getSkuCode()+"]分配的领新数量不够");
                throw new BusinessException("SKU["+e.getSkuCode()+"]分配的领新数量不够");
            }

        });
        return useInventoryInoutDetailForm.getDetailList();
    }

    void getOptimalLanes(UseInventoryInoutDetailForm useInventoryInoutDetailForm) {
//        SystemRuleInfo systemRuleInfo=systemRuleInfoService.getOne(new QueryWrapper<SystemRuleInfo>());
        SystemRuleInfo systemRuleInfo=systemRuleInfoService.getRuleInfo();
        Boolean hasTargetQuantity=true;
        Boolean isEmpty=true;
        useInventoryInoutDetailForm.setIsEmpty(isEmpty);
        Boolean outOrderFlag=true;
        if (systemRuleInfo!=null){
            outOrderFlag=systemRuleInfo.getOutOrderFlag();
        }
        Map paramMap=new HashMap();
        String[] cabCodes=useInventoryInoutDetailForm.getCabCode().split(",");
        for (UseInventoryInoutDetailForm item:useInventoryInoutDetailForm.getDetailList()){
            if (item.getQuantity()<=0){
                continue;
            }
            paramMap.put("skuCode4app",item.getSkuCode());
            paramMap.put("cabCodes",cabCodes);
            paramMap.put("quantityPackUnit",item.getQuantityPackUnit());
            paramMap.put("sort","asc");
//                paramMap.put("quantity4Query",item.getQuantity());
            List<CellInventorySpaceVO> cellInventorySpaceVOS=baseMapper.listOptimalSpace4app(paramMap);
            if (cellInventorySpaceVOS.size()==0
//                    ||getSumQuantity(cellInventorySpaceVOS)<item.getQuantity()
            ){
//                throw new BusinessException("SKU["+item.getSkuCode()+"]货不足");
                continue;
            }
            isEmpty=false;
            item.setQuantityTarget(item.getQuantity());
            useInventoryInoutDetailForm.getQuantityTargetList().add(item.getQuantityTarget());
            item.setQuantityExist(getSumQuantity(cellInventorySpaceVOS));
            useInventoryInoutDetailForm.getQuantityExistList().add(item.getQuantityExist());
            item.setQuantityByLane(item.getQuantityExist());
            item.setQuantitySurplus(item.getQuantityTarget()-item.getQuantityExist());

            useInventoryInoutDetailForm.getQuantitySurplusList().add(item.getQuantitySurplus());

            if (item.getQuantityExist()<item.getQuantity()){
                item.setQuantity(item.getQuantityExist());
            }
            if (item.getQuantitySurplus()>0){
                hasTargetQuantity=false;
            }
            item.setLaneList(cellInventorySpaceVOS);

            Map<String,List<CellInventorySpaceVO>> spaceMap= getAvaiableCab(item.getLaneList(),item.getQuantity());
            if(null != spaceMap) {
                item.setCabSpacesMap(spaceMap);
            }else{
                item.setCabSpacesMap(new HashMap<String,List<CellInventorySpaceVO>>());
            }
            if(null != spaceMap.keySet()) {
                item.setCabCodesSet(spaceMap.keySet());
            }else{
                item.setCabCodesSet(new HashSet<String>());
            }
        }
        if (isEmpty){
            useInventoryInoutDetailForm.setIsEmpty(isEmpty);
            useInventoryInoutDetailForm.setHasTargetQuantity(false);
            return;
        }
        String optimalCabCode=getOptimalCab(useInventoryInoutDetailForm.getDetailList());
        for (UseInventoryInoutDetailForm item:useInventoryInoutDetailForm.getDetailList()){
            if (item.getCabSpacesMap().containsKey(optimalCabCode)){
                List<CellInventorySpaceVO> sortList=item.getCabSpacesMap().get(optimalCabCode);
                Collections.sort(sortList);
                item.setResultLaneList(sortList);
            }else{
                if (item.getCabCodesSet().size()>0){
                    List<CellInventorySpaceVO> sortList=item.getCabSpacesMap().get(item.getCabCodesSet().iterator().next());
                    Collections.sort(sortList);
                    item.setResultLaneList(sortList);
                }else{
                    item.setResultLaneList(item.getLaneList());
                    List<CabSortInventorySpaceVO> sortList=getCabSpaces(item.getLaneList());
                    Collections.sort(sortList);
                    item.setSortCabList(sortList);
                }

            }
            if (outOrderFlag){
                item.setResultLaneList(getSpaceByLanePullFull(item));
            }else{
                item.setResultLaneList(getSpaceByLanePoll(item,optimalCabCode));
            }
        }
        Map errerMap=new HashMap();
        useInventoryInoutDetailForm.getDetailList().forEach(e->{
            e.setLaneList(null);
            e.setCabSpacesMap(null);
            e.setCabCodesSet(null);
            e.setSortCabList(null);
            //test
            e.setQuantityResult(getSumQuantity(e.getResultLaneList()));
            if (!e.getQuantity().equals(e.getQuantityResult())){
//                log.error("get optimal space fail:{}","SKU["+e.getSkuCode()+"]分配的领新数量不够");
//                throw new BusinessException("SKU["+e.getSkuCode()+"]分配的领新数量不够");
                errerMap.put(e.getSkuCode(),e);
            }

        });
        if (errerMap.size()>0){
//            return null;
        }
        useInventoryInoutDetailForm.setHasTargetQuantity(hasTargetQuantity);
//        return useInventoryInoutDetailForm.getDetailList();
    }

    private List<UseInventoryInoutDetailForm> getOptimalLanesFull(UseInventoryInoutDetailForm useInventoryInoutDetailForm) {
//        SystemRuleInfo systemRuleInfo=systemRuleInfoService.getOne(new QueryWrapper<SystemRuleInfo>());
        SystemRuleInfo systemRuleInfo=systemRuleInfoService.getRuleInfo();
        Boolean outOrderFlag=true;
        if (systemRuleInfo!=null){
            outOrderFlag=systemRuleInfo.getOutOrderFlag();
        }
        Map paramMap=new HashMap();
        String[] cabCodes=useInventoryInoutDetailForm.getCabCode().split(",");
        for (UseInventoryInoutDetailForm item:useInventoryInoutDetailForm.getDetailList()){
            paramMap.put("skuCode4app",item.getSkuCode());
            paramMap.put("cabCodes",cabCodes);
            paramMap.put("quantityPackUnit",item.getQuantityPackUnit());
            paramMap.put("sort","asc");
//                paramMap.put("quantity4Query",item.getQuantity());
            List<CellInventorySpaceVO> cellInventorySpaceVOS=baseMapper.listOptimalSpace4app(paramMap);
            if (cellInventorySpaceVOS.size()==0||getSumQuantity(cellInventorySpaceVOS)<item.getQuantity()){
//                throw new BusinessException("SKU["+item.getSkuCode()+"]货不足");
//                return null;
            }
            item.setQuantityTarget(item.getQuantity());
            item.setQuantityExist(getSumQuantity(cellInventorySpaceVOS));
            item.setQuantitySurplus(item.getQuantityTarget()-item.getQuantityExist());
            item.setLaneList(cellInventorySpaceVOS);

            Map<String,List<CellInventorySpaceVO>> spaceMap= getAvaiableCab(item.getLaneList(),item.getQuantity());
            item.setCabSpacesMap(spaceMap);
            item.setCabCodesSet(spaceMap.keySet());
        }

        String optimalCabCode=getOptimalCab(useInventoryInoutDetailForm.getDetailList());
        for (UseInventoryInoutDetailForm item:useInventoryInoutDetailForm.getDetailList()){
            if (item.getCabSpacesMap().containsKey(optimalCabCode)){
                List<CellInventorySpaceVO> sortList=item.getCabSpacesMap().get(optimalCabCode);
                Collections.sort(sortList);
                item.setResultLaneList(sortList);
            }else{
                if (item.getCabCodesSet().size()>0){
                    List<CellInventorySpaceVO> sortList=item.getCabSpacesMap().get(item.getCabCodesSet().iterator().next());
                    Collections.sort(sortList);
                    item.setResultLaneList(sortList);
                }else{
                    item.setResultLaneList(item.getLaneList());
                    List<CabSortInventorySpaceVO> sortList=getCabSpaces(item.getLaneList());
                    Collections.sort(sortList);
                    item.setSortCabList(sortList);
                }

            }
            if (outOrderFlag){
                item.setResultLaneList(getSpaceByLanePullFull(item));
            }else{
                item.setResultLaneList(getSpaceByLanePoll(item,optimalCabCode));
            }
        }
        Map errerMap=new HashMap();
        useInventoryInoutDetailForm.getDetailList().forEach(e->{
            e.setLaneList(null);
            e.setCabSpacesMap(null);
            e.setCabCodesSet(null);
            e.setSortCabList(null);
            //test
            e.setQuantityResult(getSumQuantity(e.getResultLaneList()));
            if (!e.getQuantity().equals(e.getQuantityResult())){
//                log.error("get optimal space fail:{}","SKU["+e.getSkuCode()+"]分配的领新数量不够");
//                throw new BusinessException("SKU["+e.getSkuCode()+"]分配的领新数量不够");
                errerMap.put(e.getSkuCode(),e);
            }

        });
        if (errerMap.size()>0){
//            return null;
        }
        return useInventoryInoutDetailForm.getDetailList();
    }

    @Override
    public List<CabOptimalSpaces> getCabOptimalSpaces(UseInventoryInoutDetailForm useInventoryInoutDetailForm) {
        List<UseInventoryInoutDetailForm> skuLaneList=this.getOptimalSpaces(useInventoryInoutDetailForm);
//        Map<String,List<CellInventorySpaceVO>> resultMap=new HashMap<>();
//        Map<String,List<Integer>> cabSpaceCodeMap=new LinkedHashMap<>();
//        Map<String,CabQuantityVO> cabCodeQuantityMap=new HashMap<>();
//        for (UseInventoryInoutDetailForm item:skuLaneList){
//            for (CellInventorySpaceVO cellInventorySpace:item.getResultLaneList()){
//                Integer spaceCodeKey=Integer.valueOf(cellInventorySpace.getSpaceCode())/10;
//                String cabCode=cellInventorySpace.getCabCode();
//                String key=cabCode+"_"+spaceCodeKey;
//                List<CellInventorySpaceVO> tempList=resultMap.get(key);
//
//                if (tempList!=null){
//                    tempList.add(cellInventorySpace);
//                }else{
//                    tempList=new ArrayList<>();
//                    tempList.add(cellInventorySpace);
//                    resultMap.put(key,tempList);
//                }
//                CabQuantityVO cabQuantityVO=cabCodeQuantityMap.get(cabCode);
//                if (cabQuantityVO==null){
//                    cabQuantityVO=new CabQuantityVO();
//                    cabQuantityVO.setCabCode(cabCode);
//                    cabQuantityVO.setQuantity(cellInventorySpace.getQuantity());
//                    cabCodeQuantityMap.put(cabCode,cabQuantityVO);
//                }else{
//                    cabQuantityVO.setQuantity(cabQuantityVO.getQuantity()+cellInventorySpace.getQuantity());
//                    cabCodeQuantityMap.put(cabCode,cabQuantityVO);
//                }
//                List<Integer> spaceCodeList=cabSpaceCodeMap.get(cabCode);
//                if (spaceCodeList!=null){
//                    if (!spaceCodeList.contains(spaceCodeKey)){
//                        spaceCodeList.add(spaceCodeKey);
//                    }
//                }else{
//                    spaceCodeList=new ArrayList<>();
//                    spaceCodeList.add(spaceCodeKey);
//                    cabSpaceCodeMap.put(cabCode,spaceCodeList);
//                }
//            }
//        }
//        List<CabOptimalSpaces> resultList=new ArrayList<>();
//        /**
//        resultMap.keySet().forEach(e->{
//            CabOptimalSpaces cabOptimalSpaces=new CabOptimalSpaces();
//            cabOptimalSpaces.setCabCode(e);
//
//            Map<Integer,List<CellInventorySpaceVO>> spaceMap=new HashMap<>();
//            List<Integer> spaceCodeKeyList=new ArrayList<>();
//            for (CellInventorySpaceVO cellInventorySpaceVO:resultMap.get(e)){
//                Integer spaceCodeKey=Integer.valueOf(cellInventorySpaceVO.getSpaceCode())/10;
//                List<CellInventorySpaceVO> tempList=spaceMap.get(spaceCodeKey);
//                if (tempList!=null){
//                    tempList.add(cellInventorySpaceVO);
//                }else{
//                   tempList=new ArrayList<>();
//                   tempList.add(cellInventorySpaceVO);
//                   spaceMap.put(spaceCodeKey,tempList);
//                }
//            }
//            Collections.sort(spaceCodeKeyList);
//            List<CellInventorySpaceVO> resultLaneList=new ArrayList<>();
//            for (Integer spaceCodeKey:spaceCodeKeyList){
//                resultLaneList.addAll(spaceMap.get(spaceCodeKey));
//            }
//            cabOptimalSpaces.setResultLaneList(resultLaneList);
//
//            resultList.add(cabOptimalSpaces);
//        });
//         */
//        List<CabQuantityVO> cabQuantityList=new ArrayList<>();
//        cabCodeQuantityMap.forEach((key,val)->{
//            cabQuantityList.add(val);
//        });
//        Collections.sort(cabQuantityList);
//        cabQuantityList.forEach(e->{
//            String cabCode=e.getCabCode();
//            List<Integer> spaceCodeKyList=cabSpaceCodeMap.get(cabCode);
//            CabOptimalSpaces cabOptimalSpaces=new CabOptimalSpaces();
//            cabOptimalSpaces.setCabCode(cabCode);
//            Collections.sort(spaceCodeKyList);
//            List<CellInventorySpaceVO> resultLaneList=new ArrayList<>();
//            spaceCodeKyList.forEach(spaceCodeKey->{
//                resultLaneList.addAll(resultMap.get(cabCode+"_"+spaceCodeKey));
//            });
//            cabOptimalSpaces.setResultLaneList(resultLaneList);
//            resultList.add(cabOptimalSpaces);
//        });
        List<CabOptimalSpaces> resultList=sortSpaces(skuLaneList);
        return resultList;
    }

    public SpacesResultVO getCabOptimalLanesSpaces(UseInventoryInoutDetailForm useInventoryInoutDetailForm) {
        SystemRuleInfo systemRuleInfo=systemRuleInfoService.getRuleInfo();
        Boolean outFistCellCabFlag=true;
        if (systemRuleInfo!=null){
            outFistCellCabFlag=systemRuleInfo.getOutFirstCellCabFlag();
        }
        if (outFistCellCabFlag){
            this.getOptimalLanes(useInventoryInoutDetailForm);
            List<UseInventoryInoutDetailForm> skuLaneList=useInventoryInoutDetailForm.getDetailList();
            SpacesResultVO spacesResultVO=new SpacesResultVO();
            List<CabOptimalSpaces> resultList=sortSpaces(skuLaneList);
            spacesResultVO.setLaneList(resultList);
            if (useInventoryInoutDetailForm.getHasTargetQuantity()){
                return spacesResultVO;
            }else{
                if(null != useInventoryInoutDetailForm.getDetailList() && useInventoryInoutDetailForm.getDetailList().size() != 0) {
                    useInventoryInoutDetailForm.getDetailList().forEach(e -> {
                        if(null != e.getQuantityTarget() && null != e.getQuantityExist()) {
                            e.setQuantity(e.getQuantityTarget() - e.getQuantityExist());
                        }
                    });
                }
                storageInventorySpaceService.getOptimalSpaces(useInventoryInoutDetailForm);
                if (useInventoryInoutDetailForm.getHasTargetQuantity()){
                    skuLaneList=useInventoryInoutDetailForm.getDetailList();
                    List<CabOptimalSpaces> resultSpaceList=storageInventorySpaceService.sortSpaces(skuLaneList);
                    spacesResultVO.setSpaceList(resultSpaceList);
                    return spacesResultVO;
                }
                for (UseInventoryInoutDetailForm item:useInventoryInoutDetailForm.getDetailList()){
                    if (item.getQuantitySurplus() == null || item.getQuantitySurplus()>0){
                        throw new BusinessException("物料编号["+item.getSkuCode()+"]库存不足");
                    }
                }
            }
        }else{
            SpacesResultVO spacesResultVO=new SpacesResultVO();
            storageInventorySpaceService.getOptimalSpaces(useInventoryInoutDetailForm);
            List<UseInventoryInoutDetailForm> skuLaneList=useInventoryInoutDetailForm.getDetailList();
            List<CabOptimalSpaces> resultSpaceList=null;
            if (!useInventoryInoutDetailForm.getIsEmpty()){
                resultSpaceList=storageInventorySpaceService.sortSpaces(skuLaneList);
            }

            if (useInventoryInoutDetailForm.getHasTargetQuantity()){
                spacesResultVO.setSpaceList(resultSpaceList);
                return spacesResultVO;
            }else{
                this.getOptimalLanes(useInventoryInoutDetailForm);
                if (useInventoryInoutDetailForm.getHasTargetQuantity()){
                    skuLaneList=useInventoryInoutDetailForm.getDetailList();
                    List<CabOptimalSpaces> resultList=sortSpaces(skuLaneList);
                    spacesResultVO.setLaneList(resultList);
                    return spacesResultVO;
                }
                for (UseInventoryInoutDetailForm item:useInventoryInoutDetailForm.getDetailList()){
                    if (item.getQuantitySurplus() == null || item.getQuantitySurplus()>0){
                        throw new BusinessException("物料编号["+item.getSkuCode()+"]库存不足");
                    }
                }
            }
        }


        return null;
//        return resultList;
    }



    private List<CabOptimalSpaces> sortSpaces(List<UseInventoryInoutDetailForm> skuLaneList){
        Map<String,List<CellInventorySpaceVO>> resultMap=new HashMap<>();
        Map<String,List<Integer>> cabSpaceCodeMap=new LinkedHashMap<>();
        Map<String,CabQuantityVO> cabCodeQuantityMap=new HashMap<>();
        for (UseInventoryInoutDetailForm item:skuLaneList){
            if (item.getResultLaneList()!=null){
                for (CellInventorySpaceVO cellInventorySpace:item.getResultLaneList()){
                    Integer spaceCodeKey=Integer.valueOf(cellInventorySpace.getSpaceCode())/10;
                    String cabCode=cellInventorySpace.getCabCode();
                    String key=cabCode+"_"+spaceCodeKey;
                    List<CellInventorySpaceVO> tempList=resultMap.get(key);

                    if (tempList!=null){
                        tempList.add(cellInventorySpace);
                    }else{
                        tempList=new ArrayList<>();
                        tempList.add(cellInventorySpace);
                        resultMap.put(key,tempList);
                    }
                    CabQuantityVO cabQuantityVO=cabCodeQuantityMap.get(cabCode);
                    if (cabQuantityVO==null){
                        cabQuantityVO=new CabQuantityVO();
                        cabQuantityVO.setCabCode(cabCode);
                        cabQuantityVO.setQuantity(cellInventorySpace.getQuantity());
                        cabCodeQuantityMap.put(cabCode,cabQuantityVO);
                    }else{
                        cabQuantityVO.setQuantity(cabQuantityVO.getQuantity()+cellInventorySpace.getQuantity());
                        cabCodeQuantityMap.put(cabCode,cabQuantityVO);
                    }
                    List<Integer> spaceCodeList=cabSpaceCodeMap.get(cabCode);
                    if (spaceCodeList!=null){
                        if (!spaceCodeList.contains(spaceCodeKey)){
                            spaceCodeList.add(spaceCodeKey);
                        }
                    }else{
                        spaceCodeList=new ArrayList<>();
                        spaceCodeList.add(spaceCodeKey);
                        cabSpaceCodeMap.put(cabCode,spaceCodeList);
                    }
                }
            }

        }
        List<CabOptimalSpaces> resultList=new ArrayList<>();
        /**
         resultMap.keySet().forEach(e->{
         CabOptimalSpaces cabOptimalSpaces=new CabOptimalSpaces();
         cabOptimalSpaces.setCabCode(e);

         Map<Integer,List<CellInventorySpaceVO>> spaceMap=new HashMap<>();
         List<Integer> spaceCodeKeyList=new ArrayList<>();
         for (CellInventorySpaceVO cellInventorySpaceVO:resultMap.get(e)){
         Integer spaceCodeKey=Integer.valueOf(cellInventorySpaceVO.getSpaceCode())/10;
         List<CellInventorySpaceVO> tempList=spaceMap.get(spaceCodeKey);
         if (tempList!=null){
         tempList.add(cellInventorySpaceVO);
         }else{
         tempList=new ArrayList<>();
         tempList.add(cellInventorySpaceVO);
         spaceMap.put(spaceCodeKey,tempList);
         }
         }
         Collections.sort(spaceCodeKeyList);
         List<CellInventorySpaceVO> resultLaneList=new ArrayList<>();
         for (Integer spaceCodeKey:spaceCodeKeyList){
         resultLaneList.addAll(spaceMap.get(spaceCodeKey));
         }
         cabOptimalSpaces.setResultLaneList(resultLaneList);

         resultList.add(cabOptimalSpaces);
         });
         */
        List<CabQuantityVO> cabQuantityList=new ArrayList<>();
        cabCodeQuantityMap.forEach((key,val)->{
            cabQuantityList.add(val);
        });
        Collections.sort(cabQuantityList);
        cabQuantityList.forEach(e->{
            String cabCode=e.getCabCode();
            List<Integer> spaceCodeKyList=cabSpaceCodeMap.get(cabCode);
            CabOptimalSpaces cabOptimalSpaces=new CabOptimalSpaces();
            cabOptimalSpaces.setCabCode(cabCode);
            Collections.sort(spaceCodeKyList);
            List<CellInventorySpaceVO> resultLaneList=new ArrayList<>();
            spaceCodeKyList.forEach(spaceCodeKey->{
                resultLaneList.addAll(resultMap.get(cabCode+"_"+spaceCodeKey));
            });
            cabOptimalSpaces.setResultLaneList(resultLaneList);
            resultList.add(cabOptimalSpaces);
        });
        return resultList;
    }

    private List<CabSortInventorySpaceVO> getCabSpaces(List<CellInventorySpaceVO> list){
        List<CabSortInventorySpaceVO> sortList=new ArrayList<>();
        if (list.size()==0){
            return sortList;
        }
        Integer sum=0;
        String preCab=list.get(0).getCabCode();
        List<CellInventorySpaceVO> tempList=new ArrayList<>();
        for (CellInventorySpaceVO cellInventorySpaceVO:list){
            String nextCab=cellInventorySpaceVO.getCabCode();
            if (preCab.equals(nextCab)){
                sum+=cellInventorySpaceVO.getQuantity();
                tempList.add(cellInventorySpaceVO);
            }else{
                CabSortInventorySpaceVO cabSortInventorySpaceVO=new CabSortInventorySpaceVO();
                cabSortInventorySpaceVO.setQuantity(sum);
                cabSortInventorySpaceVO.setSpaceList(tempList);
                cabSortInventorySpaceVO.setCabCode(preCab);
                sortList.add(cabSortInventorySpaceVO);
                preCab=nextCab;
                sum=cellInventorySpaceVO.getQuantity();
                tempList=new ArrayList<>();
                tempList.add(cellInventorySpaceVO);
            }
        }
        CabSortInventorySpaceVO cabSortInventorySpaceVO=new CabSortInventorySpaceVO();
        cabSortInventorySpaceVO.setQuantity(sum);
        cabSortInventorySpaceVO.setSpaceList(tempList);
        cabSortInventorySpaceVO.setCabCode(preCab);
        sortList.add(cabSortInventorySpaceVO);
        return sortList;
    }

    private List<CellInventorySpaceVO> getSpaceByLanePullFull(UseInventoryInoutDetailForm useInventoryInoutDetailForm){

        List<CellInventorySpaceVO> spaceList=new ArrayList<>();
        Integer quantity=useInventoryInoutDetailForm.getQuantity();
        if (CollectionUtil.isNotEmpty(useInventoryInoutDetailForm.getSortCabList())){
            L1:for (int i=0;i<useInventoryInoutDetailForm.getSortCabList().size();i++){
                CabSortInventorySpaceVO cabSortInventorySpaceVO=useInventoryInoutDetailForm.getSortCabList().get(i);
                List<CellInventorySpaceVO> cabSpaceList= cabSortInventorySpaceVO.getSpaceList();
//                if (i>0){
                    Collections.sort(cabSpaceList);
//                }
                for (CellInventorySpaceVO item:cabSpaceList){
                    if (item.getQuantity()>=quantity){
                        item.setQuantity(quantity);
                        spaceList.add(item);
                        break L1;
                    }else{
                        spaceList.add(item);
                        quantity=quantity-item.getQuantity();
                    }
                }
            }
        }else{
            if (useInventoryInoutDetailForm.getResultLaneList()!=null){
                for (CellInventorySpaceVO item:useInventoryInoutDetailForm.getResultLaneList()){
                    if (item.getQuantity()>=quantity){
                        item.setQuantity(quantity);
                        spaceList.add(item);
                        break;
                    }else{
                        spaceList.add(item);
                        quantity=quantity-item.getQuantity();
                    }
                }
            }

        }

        return spaceList;
    }


    private List<CellInventorySpaceVO> getSpaceByLanePoll(UseInventoryInoutDetailForm useInventoryInoutDetailForm,String optimalCabCode){
        List<CellInventorySpaceVO> spaceList=new ArrayList<>();
        Integer quantity=useInventoryInoutDetailForm.getQuantity();
        Integer sum=0;
//        if (useInventoryInoutDetailForm.getCabSpacesMap().containsKey(optimalCabCode)){
        if (CollectionUtil.isEmpty(useInventoryInoutDetailForm.getSortCabList())){
            boolean isReturn=false;
//            List<CellInventorySpaceVO> cellInventorySpaceVOS=useInventoryInoutDetailForm.getCabSpacesMap().get(optimalCabCode);
            List<CellInventorySpaceVO> cellInventorySpaceVOS=useInventoryInoutDetailForm.getResultLaneList();
            L1:while (true){
                Integer zeroQuantitySum=0;
                L2:for (CellInventorySpaceVO item:cellInventorySpaceVOS){
                    if (item.getQuantity()==0){
                        ++zeroQuantitySum;
                        if (zeroQuantitySum==useInventoryInoutDetailForm.getResultLaneList().size()){
                            break L1;
                        }
                        continue;
                    }
                    spaceList.add(item);
                    item.setQuantity(item.getQuantity()-1);
                    ++sum;
                    if (sum==quantity){
                        isReturn=true;
                        break L1;
                    }
                }
            }
            if (isReturn){
                spaceList.forEach(item->{
                    item.setQuantity(1);
                });
                return spaceList;
            }
        }else{
            boolean isReturn=false;

//            if (CollectionUtil.isNotEmpty(useInventoryInoutDetailForm.getSortCabList())){
                L3:for (CabSortInventorySpaceVO cabSortInventorySpaceVO:useInventoryInoutDetailForm.getSortCabList()){
//                    if (optimalCabCode.equals(cabSortInventorySpaceVO.getCabCode())){
//                        continue ;
//                    }
                    List<CellInventorySpaceVO> cabSpacesList=cabSortInventorySpaceVO.getSpaceList();
                    Collections.sort(cabSpacesList);
                    L4:while (true){
                        Integer zeroQuantitySum=0;
                        L5:for (CellInventorySpaceVO item:cabSpacesList){
                            if (item.getQuantity()==0){
                                ++zeroQuantitySum;
                                if (zeroQuantitySum==cabSortInventorySpaceVO.getSpaceList().size()){
                                    break L4;
                                }
                                continue;
                            }
                            spaceList.add(item);
                            item.setQuantity(item.getQuantity()-1);
                            ++sum;
                            if (sum==quantity){
                                isReturn=true;
                                break L3;
                            }
                        }
                    }


                }
//            }


            if (isReturn){
                spaceList.forEach(item->{
                    item.setQuantity(1);
                });
                return spaceList;
            }
        }

        throw new BusinessException("SKU["+useInventoryInoutDetailForm.getSkuCode()+"]货不足");
    }

    private String getOptimalCab(List<UseInventoryInoutDetailForm> detailList){
        if (detailList.size()==1){
            if (detailList.get(0).getCabCodesSet()!=null&&detailList.get(0).getCabCodesSet().size()>0){
                Integer quantity=Integer.MAX_VALUE;
                String cabCode=null;
                Iterator<String> iterator=detailList.get(0).getCabCodesSet().iterator();
                while (iterator.hasNext()){
                    String nextCabCode=iterator.next();
                    List<CellInventorySpaceVO> cellInventorySpaceVOS=detailList.get(0).getCabSpacesMap().get(nextCabCode);
                    Integer nextQuantity=getSumQuantity(cellInventorySpaceVOS);
                    if (nextQuantity<quantity){
                        quantity=nextQuantity;
                        cabCode=nextCabCode;
                    }
                }
                if (cabCode!=null){
                    return cabCode;
                }
            }

        }
        Map<String,Integer> cabCodesMap=new HashMap<>();
        for (UseInventoryInoutDetailForm item:detailList){
            if(null == item.getCabCodesSet()) continue;
            item.getCabCodesSet().forEach(e->{
                if(cabCodesMap.containsKey(e)){
                    cabCodesMap.put(e,cabCodesMap.get(e)+1);
                }else{
                    cabCodesMap.put(e,1);
                }
            });
        }
        Set<String> cabCodeSet=cabCodesMap.keySet();
        Integer maxVal=0;
        String optimalCabCode="";
        for(String cabCode:cabCodeSet){
            Integer val=cabCodesMap.get(cabCode);
            if (val>maxVal){
                optimalCabCode=cabCode;
                maxVal=val;
            }
        }
        return optimalCabCode;
    }

    private Map<String,List<CellInventorySpaceVO>> getAvaiableCab(List<CellInventorySpaceVO> list, Integer quantity){
        Map<String,List<CellInventorySpaceVO>> resultMap=new HashMap<>();
        if (list.size()==0){
            return resultMap;
        }
        Integer sum=0;
        String preCab=list.get(0).getCabCode();
        List<CellInventorySpaceVO> tempList=new ArrayList<>();
        for (CellInventorySpaceVO cellInventorySpaceVO:list){
            String nextCab=cellInventorySpaceVO.getCabCode();
            if (preCab.equals(nextCab)){
                sum+=cellInventorySpaceVO.getQuantity();
                tempList.add(cellInventorySpaceVO);
            }else{
                if (sum>=quantity){
                    resultMap.put(preCab,tempList);
                }
                preCab=nextCab;
                sum=cellInventorySpaceVO.getQuantity();
                tempList=new ArrayList<>();
                tempList.add(cellInventorySpaceVO);
            }
        }
        if (sum>=quantity){
            resultMap.put(preCab,tempList);
        }
        return resultMap;
    }



    private Integer getSumQuantity(List<CellInventorySpaceVO> list){
        Integer sum=0;
        for (CellInventorySpaceVO cellInventorySpaceVO:list){
            sum+=cellInventorySpaceVO.getQuantity();
        }
        return sum;
    }

    @Override
    public CellInventorySpaceVO get4appById(Long id) {
        return baseMapper.get4appById(id);
    }

    @Override
    public List<CellInventorySpaceVO> getAlarmProduct(List<CellInventorySpaceVO> listRecords) {
        for (CellInventorySpaceVO item : listRecords) {
            QueryWrapper<CabAlarmSettings> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("cab_code",item.getCabCode()).eq("sku_code",item.getSkuCode());
            CabAlarmSettings alarm = cabAlarmSettingsService.getOne(queryWrapper);
            if(Objects.nonNull(alarm)) {
                item.setAlarmStock(alarm.getAlarmStock())
                        .setPlanReplenishment(alarm.getPlanReplenishment())
                        .setProposalStock(alarm.getProposalStock());
            }
            QueryWrapper<CellInventorySpace> queryWrapperSpace = new QueryWrapper<>();
            queryWrapperSpace.eq("cab_code",item.getCabCode()).eq("sku_code",item.getSkuCode());
            int count = this.count(queryWrapperSpace);
            if(count > 0){
                item.setCargoLaneNum(count);
            }


        }
        return listRecords;
    }

    @Override
    public List<CellInventorySpaceVO> ecxportList(Map<String, Object> params) {
        return baseMapper.list(params);
    }

    @Override
    public Integer getSumByParams(String mainCabCode, String cabCode, String skuCode) {
        return baseMapper.getSumByParams(mainCabCode, cabCode, skuCode);
    }
}
